function calculateArea(width, scale, accuracy, bool, isArert, lengthOnly, mergeSimilar, ifInsertCTS) {
  var materialWidth = width;
  var drawingScale = scale;
  var dataAccuracy = accuracy;
  var isAddExtraText = bool;
  var isAlertResult = isArert;
  var ifOutputLengthOnly = lengthOnly;
  var ifMergeSimilarLength = mergeSimilar;
  var ifInsertCreationTimeStamp = ifInsertCTS;
  // 转换单位
  // 实际大小
  function pointToMM(numIn) {
    return (numIn / 72) * 25.4;
  }
  function MMTopoint(numIn) {
    return (numIn / 25.4) * 72;
  }
  // 转换成米，生产大小
  function pointToM(numIn) {
    return (((numIn / 72) * 25.4) / 1000) * drawingScale;
  }
  // 转换成点
  function MTopoint(numIn) {
    return (((numIn * 1000) / 25.4) * 72) / drawingScale;
  }
  var cutCube = [];
  var length = 0;
  var area = 0;
  // 检查是否有打开的文档
  if (documents.length > 0) {
    var activeDocument = app.activeDocument;
    var elementsSelected = activeDocument.selection;
    if (elementsSelected.length > 0) {
      var arrayIndex = 0;
      // 遍历所有选中项
      for (i = 0; i < elementsSelected.length; i++) {
        var targetItem = elementsSelected[i];
        // 将选中项的名称和有效长度储存在数组中
        // length属性获得pathItem的周长, 理想情况下, 一边是材料宽幅, 另一边是打印长度
        // 需要保证选中项都为有效对象, 且宽幅一致
        var formattedLength = trimEndZero(formatNum(pointToM(targetItem.length) / 2 - materialWidth, 3));
        if (i != 0 && (formattedLength == cutCube[arrayIndex - 1][1]) && ifMergeSimilarLength) {
          var lastCubeName = cutCube[arrayIndex - 1][0].split('-');
          if (lastCubeName.length > 1) {
            lastCubeName = parseInt(lastCubeName[1]);
          } else {
            lastCubeName = parseInt(lastCubeName[0]);
          }
          if (targetItem.name == lastCubeName + 1) {
            // 序号连续，合并名称
            var cutCubeName = cutCube[arrayIndex - 1][0].split('-');
            if (cutCubeName[0] != "") {
              cutCube[arrayIndex - 1][0] = cutCubeName[0] + "-" + targetItem.name;
            }
            // 增加条数
            cutCube[arrayIndex - 1][2]++;
          } else {
            // 序号不连续，独立处理
            cutCube[arrayIndex] = [targetItem.name, formattedLength, 1];
            arrayIndex++;
          }
        } else {
          cutCube[arrayIndex] = [targetItem.name, formattedLength, 1];
          arrayIndex++;
        }

        targetItem.selected = false;
      }

      // 计算总长度
      for (j = 0; j < cutCube.length; j++) {
        length += (cutCube[j][1] * cutCube[j][2]);
      }
      // 计算总面积
      area = length * materialWidth;

      // 判断末尾是否为0, 不是则进一
      length = formatNum(length, dataAccuracy);
      area = formatNum(area, dataAccuracy);
      if (area > 0 || length > 0) {
        // 生成面积/长度文本
        var outputText = elementsSelected[0].parent.textFrames.add();
        outputText.selected = true;
        // 获取储存的长度信息
        var textContent = "";
        for (m = 0; m < cutCube.length; m++) {
          if (cutCube[m][0] != "") {
            // 每条长度
            if (ifOutputLengthOnly) {
              textContent = textContent + "[" + cutCube[m][0] + "]" + cutCube[m][1] + "---" + cutCube[m][2] + "\n";
            } else {
              if (m == 0) {
                textContent = textContent + "[" + cutCube[m][0] + "]" + materialWidth + "x" + cutCube[m][1] + "---" + cutCube[m][2] + "\n";
              } else {
                // 判断序号是否连续，不连续则补充缺失序号
                // 提取最后一行文本“[1-3]1.8x10---30”中括号内-后面的数字，跟cutCube[m][0]-前面的数字比较，如果不是相差1，则添加一行文本"[后面的数字+1]"
                var stringContainsLastNum = textContent.split("\n")[textContent.split("\n").length - 2].split("]")[0].split("[")[1];
                var lastNum = 0;
                if (stringContainsLastNum.split("-").length > 1) {
                  lastNum = parseInt(stringContainsLastNum.split("-")[1]);
                } else {
                  lastNum = parseInt(stringContainsLastNum);
                }

                var cutCubeName = cutCube[m][0].split('-');
                var currentStartNumber = cutCubeName[0];
                var currentNum = lastNum + 1;

                if (currentStartNumber - 1 != lastNum) {
                  textContent = textContent + "[" + currentNum + "]" + "\n";
                }
                textContent = textContent + "[" + cutCube[m][0] + "]" + materialWidth + "x" + cutCube[m][1] + "---" + cutCube[m][2] + "\n";
              }
            }
            if (m == cutCube.length - 1) {
              if (isAddExtraText) {
                textContent = textContent + "余料补齐\n";
              }
              // 末尾汇总
              if (ifOutputLengthOnly) {
                textContent = textContent + "总长度：" + length + "m";
              } else {
                textContent = textContent + "打印面积：" + area + "m²";
              }
              // 末行时间戳
              if (ifInsertCreationTimeStamp) {
                textContent = getTimeStampForOutput(textContent);
              }
            }
          } else {
            // 每条长度
            if (ifOutputLengthOnly) {
              textContent = textContent + cutCube[m][1] + "---" + cutCube[m][2] + "\n";
            } else {
              textContent = textContent + materialWidth + "x" + cutCube[m][1] + "---" + cutCube[m][2] + "\n";
            }
            if (m == cutCube.length - 1) {
              if (isAddExtraText) {
                textContent = textContent + "余料补齐\n";
              }
              // 末尾汇总
              if (ifOutputLengthOnly) {
                textContent = textContent + "总长度：" + length + "m";
              } else {
                textContent = textContent + "打印面积：" + area + "m²";
              }
              // 末行时间戳
              if (ifInsertCreationTimeStamp) {
                textContent = getTimeStampForOutput(textContent);
              }
            }
          }
        }
        // 传递文本内容
        outputText.contents = textContent;
        // 设置文本字体
        for (n = 0; n < app.textFonts.length; n++) {
          if (app.textFonts[n].name == "MicrosoftYaHei") {
            outputText.textRange.characterAttributes.textFont = app.textFonts[n];
          }
          // 筛查illustrator中字体的实际名称
          // if(app.textFonts[n].name.indexOf("m") == 0){
          //   alert(app.textFonts[n].name);
          // }
          // if(app.textFonts[n].name.indexOf("M") == 0){
          //   alert(app.textFonts[n].name);
          // }
        }
        // artboardRect输出4个值, 前两个是左上角点的坐标, 后两个是右下角点的坐标
        // alert(activeDocument.artboards[0].artboardRect);
        // 获取画板两点坐标
        var artboardX1 = activeDocument.artboards[0].artboardRect[0];
        var artboardY1 = activeDocument.artboards[0].artboardRect[1];
        var artboardX2 = activeDocument.artboards[0].artboardRect[2];
        var artboardY2 = activeDocument.artboards[0].artboardRect[3];
        var artboardWidth = artboardX2 - artboardX1;
        var artboardHeight = artboardY1 - artboardY2;
        // 根据材料宽幅和制图比例计算文本宽、高
        var textScale;
        if (drawingScale == 1) {
          if (ifInsertCTS) {
            textScale = (MTopoint(materialWidth) * 0.6) / outputText.width;
          } else {
            textScale = (MTopoint(materialWidth) * 0.45) / outputText.width;
          }
        } else if (drawingScale == 10) {
          if (ifInsertCTS) {
            textScale = (MTopoint(materialWidth) * 3) / outputText.width;
          } else {
            textScale = (MTopoint(materialWidth) * 2.5) / outputText.width;
          }
        } else if (drawingScale == 100) {
          if (ifInsertCTS) {
            textScale = (MTopoint(materialWidth) * 3) / outputText.width;
          } else {
            textScale = (MTopoint(materialWidth) * 2.5) / outputText.width;
          }
        }
        
        try {
          outputText.width *= textScale;
          outputText.height *= textScale;
        } catch (error) {
          try {
            outputText.width *= textScale;
            outputText.height *= textScale;
          } catch (error) {
            try {
              outputText.width *= textScale;
              outputText.height *= textScale;
            } catch (error) {
              try {
                outputText.width *= textScale;
                outputText.height *= textScale;
              } catch (error) {
                outputText.width *= textScale;
                outputText.height *= textScale;
              }
            }
          }
        }

        // 设置文本坐标
        outputText.top = artboardY1 - (artboardHeight - outputText.height) + outputText.width * 0.15;
        outputText.left = artboardX1 + outputText.width * 0.2;
        redraw();
        if (isAlertResult) {
          alert("共 " + elementsSelected.length + " 条, \n" + "长度：" + length + " m, \n" + "面积：" + area + " m²");
        }
      } else {
        alert("请检查宽幅与制图比例是否正确!");
      }
    } else {
      alert("请先选中需要计算面积的切割矩形!");
    }
  } else {
    alert("请先打开一个文档!");
  }
}

function formatNum(numIn, accuracyIn) {
  var tempNum = numIn.toFixed(accuracyIn + 2).slice(0, -1);
  var tempNumString = "" + tempNum;
  var lastNum = parseInt(tempNumString.charAt(tempNumString.length - 1));
  if (lastNum != 0) {
    var zeroString = "";
    var tempString = "";
    for (k = 1; k < accuracyIn; k++) {
      zeroString += "0";
    }
    tempString = "0." + zeroString + "1";
    // 此时area为字符串
    numIn = numIn.toFixed(accuracyIn + 1).slice(0, -1);
    numIn = parseFloat(numIn) + parseFloat(tempString);
  } else {
    numIn = numIn.toFixed(accuracyIn + 1).slice(0, -1);
  }
  return numIn;
}

function trimEndZero(numIn) {
  var originString = "" + numIn;
  numIn = parseFloat(originString);
  return numIn;
}

function getTimeStamp(dateIn, formatIn) {
  var year = dateIn.getFullYear();
  var month = dateIn.getMonth() + 1;
  var date = dateIn.getDate();
  var hour = dateIn.getHours();
  var minute = dateIn.getMinutes();
  var second = dateIn.getSeconds();
  switch (formatIn) {
    case "year":
      timeStamp = year + "年";
      break;
    case "month":
      timeStamp = year + "年" + month + "月";
      break;
    case "day":
      timeStamp = year + "年" + month + "月" + date + "日";
      break;
    case "hour":
      timeStamp = year + "年" + month + "月" + date + "日" + hour + "时";
      break;
    case "minute":
      timeStamp = year + "年" + month + "月" + date + "日" + hour + "时" + minute + "分";
      break;
    case "second":
      timeStamp = year + "年" + month + "月" + date + "日" + hour + "时" + minute + "分" + second + "秒";
      break;
    default:
      timeStamp = year + "年" + month + "月" + date + "日";
      break;
  }
  return timeStamp;
}

function getTimeStampForOutput(textContentIn) {
  var isTimeStampLayerExist = false;
  var isTimeStampTextExist = false;
  //判断图层与文本的存在情况
  for (o = 0; o < activeDocument.layers.length; o++) {
    targetLayer = activeDocument.layers[o];
    if (targetLayer.name == "文档时间戳") {
      isTimeStampLayerExist = true;
      for (s = 0; s < targetLayer.textFrames.length; s++) {
        if (targetLayer.textFrames[s].name == "创建日期") {
          isTimeStampTextExist = true;
        }
      }
    }
  }
  //分情况处理
  //没图层，没文本
  if (!isTimeStampLayerExist) {
    //建立图层
    timeStampLayer = activeDocument.layers.add();
    timeStampLayer.name = "文档时间戳";
    timeStampLayer.zOrder(ZOrderMethod.SENDTOBACK);
    //创建文本
    var timeStampText = timeStampLayer.textFrames.add();
    timeStampText.name = "创建日期";
    timeStampText.contents = getTimeStamp(new Date(Date.now()), "day");
    timeStampText.top = 0;
    timeStampText.left = 0;
    redraw();
    //隐藏锁定图层
    timeStampLayer.visible = false;
    timeStampLayer.locked = true;
  }
  //有图层，没文本
  if (isTimeStampLayerExist && !isTimeStampTextExist) {
    for (v = 0; v < activeDocument.layers.length; v++) {
      targetLayer = activeDocument.layers[v];
      if (targetLayer.name == "文档时间戳") {
        //显示并解锁图层
        targetLayer.visible = true;
        targetLayer.locked = false;
        //创建文本
        var newTimeStampText = targetLayer.textFrames.add();
        newTimeStampText.name = "创建日期";
        newTimeStampText.contents = getTimeStamp(new Date(Date.now()), "day");
        newTimeStampText.top = 0;
        newTimeStampText.left = 0;
        redraw();
        //隐藏锁定图层
        targetLayer.visible = false;
        targetLayer.locked = true;
      }
    }
  }
  //准备输出
  for (p = 0; p < activeDocument.layers.length; p++) {
    targetLayer = activeDocument.layers[p];
    if (targetLayer.name == "文档时间戳") {
      if (targetLayer.textFrames.length > 0) {
        for (q = 0; q < targetLayer.textFrames.length; q++) {
          if (targetLayer.textFrames[q].name == "创建日期") {
            textContentIn = textContentIn + "\n" + "创建日期：" + targetLayer.textFrames[q].contents;
          }
        }
      } else {
        textContentIn = textContentIn + "\n" + "创建日期：";
      }
    }
  }
  return textContentIn;
}
